/**
 * 品牌
 * 文件命名格式：zmn.模块名称.表名称.功能.jas
 * @author duanzucai
 * @date 2018/11/10
 */
layui.define(['index', 'form', 'table', 'laypage', 'layedit', 'laydate','jquery','zmnSelect','zmnApp', 'zmnBind'], function (exports) {
    let $ = layui.$;
    let table = layui.table;
    let laypage = layui.laypage;
    let laydate = layui.laydate;
    let form = layui.form;
    let zmnBind = layui.zmnBind;
    let zmnApp = layui.zmnApp;
    let zmnSelect = layui.zmnSelect;
    table.init('zmn-table', {
        toolbar: "#zmn-table-tool",
        page: true,
        defaultToolbar: json.showExportExcel ? ['exports'] : [], done: function () {
            $("div[lay-event='LAYTABLE_EXPORT']").attr('lay-event', 'CUSTOM_EXPORT');
        },
        limit: json.pageSize,
        height: 'full-190'
    });

    // 渲染日期范围选择器
    laydate.render({
        elem: '#timeSearch',
        range: true,
        min: json.dayLimit,
        max: 0,
        format: 'yyyy/MM/dd',
        trigger: 'click'
    });

    laypage.render(zmnPage.laypageOptions(json));

    // 部门下拉组件
    let deptTree = function (orgId) {
        if (orgId == null) {
            orgId = 0; // 后端Integer类型接收
        }
        zmnSelect.deleteXmSelect("deptId");
        let objMap = zmnSelect.select({
            'deptId': {
                isRadio: true, //单选标识：true-单选；false-多选
                selectedValues: [json.deptId == null ? '' : json.deptId], //已选中值（用于回显)
                tree: {
                    enable: true,
                    //是否展示三角图标
                    showFolderIcon: true,
                    //非严格模式
                    strict: false,
                },
                propMap: {  //选项参数映射配置
                    name: "deptName",   //显示值
                    value: "deptId"  //选中值
                },
                remote: { //远程获取下拉数据
                    enable: true, //开关：true-开启；false-关闭
                    url: json.ZMN_URL_ENV + 'mcc.xiujiadian.com/common/dept/listDeptTree.action?orgId=' + orgId, //服务url
                },
            }
        });
        objMap['deptId'].update({
            filterable: false,
            autoRow: false,
            model: {label: {type: 'text'}},
            on: function (data) {
                if (data.isAdd) {
                    return data.change.slice(0, 1)
                }
            }
        })
    }

    $(".zmn-form-cancel").click(function(){
        //$("#zmn-form")[0].reset();
        let obj = {
            "objMasterName": ""
            ,"eventName": ""
            ,"timeSearch": ""
            ,"levelId": ""
        };
        json.deptId = null;
        deptTree(json.plat);
        form.val('zmn-form',JSON.parse(JSON.stringify(obj)));
        //form.render(null, 'zmn-form');
        //form.render();
    });

    // 加载部门组件 回显部门数据
    deptTree(json.plat);

    table.on("toolbar(zmn-table)", function (obj) {

        if (obj.event === 'CUSTOM_EXPORT') {
            $("#query-export").click();
        }
    })

    form.on('submit(query-export)', function (data) {
        if (json.exportLimit === null || json.exportLimit === 0) {
            layer.msg("您没有配置导出数量，无法导出", {"icon": 2});
            return false
        }
        let index = layer.load(1, {
            shade: [0.5, '#DBDBDB'] //0.1透明度的白色背景
        });
        let dataUrl = urlEncode(data.field);
        let fileName = "绩效监控数据.xlsx";
        zmnBrs.download("/brs/record/objective/exportRecordExcel.action?" + dataUrl.slice(1), fileName, function () {
            layer.close(index);
        });
        return false;
    });

    //对外暴露的接口
    exports('brs_objective_record_list', {});
});

let zmnBrs = {
    download(url, fileName = new Date().toISOString(), done = () => {
    }) {
        fetch(url, {
            credentials: 'include'
        }).then(res => res.blob().then(blob => {
            let a = document.createElement('a');
            let url = window.URL.createObjectURL(blob);
            let filename = fileName;
            a.href = url;
            a.download = filename;
            a.click();
            window.URL.revokeObjectURL(url);
            done(blob);
        }))
    }
}

/**
 * param 将要转为URL参数字符串的对象
 * key URL参数字符串的前缀
 * encode true/false 是否进行URL编码,默认为true
 *
 * return URL参数字符串
 */
let urlEncode = function (param, key, encode) {

    if(param == null) {
        return '';
    }
    let paramStr = '';
    let t = typeof (param);
    if (t === 'string' || t === 'number' || t === 'boolean') {
        paramStr += '&' + key + '=' + ((encode == null || encode) ? encodeURIComponent(param) : param);
    } else {
        for (let i in param) {
            let k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i);
            paramStr += urlEncode(param[i], k, encode);
        }
    }
    return paramStr;
};
